package com.qiantu.phone.widget;

import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.qiantu.phone.R;
import com.qiantu.phone.app.AppApplication;

import java.util.List;

public class ViewPagerScrollIndicator extends HorizontalScrollView {

    private ViewPager viewPager;
    private ItemOnClickListener mItemOnClickListener;
    private int unselectedTextSize;
    private int selectedTextSize;
    private int itemPaddingLeft;
    private int itemPaddingRight;
    private int itemHeight;
    private MyValueAnimator mValueAnimator;
    private ArgbEvaluator argbEvaluator = null;//渐变色计算类
    private int unselectedTextColor = AppApplication.getInstance().getThemeColor(R.attr.textColor2);
    private int selectedTexColor = AppApplication.getInstance().getThemeColor(R.attr.textColor1);
    private int currentItem = 0;
    private int lastItem;
    private LinearLayout mLinearLayout;
    private int moveX;
    private int animatorDifference = 0;
    private int lastPositionOffsetPixels;
    private int startScrollX;
    private int lastPosition;
    public List<String> titles;

    public ViewPagerScrollIndicator(Context context) {
        this(context, null);
    }

    public ViewPagerScrollIndicator(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ViewPagerScrollIndicator(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = attrs == null ? null : getContext().obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator);
        if (ta != null) {
            unselectedTextSize = (int) ta.getDimension(R.styleable.ViewPagerIndicator_item_unselected_text_size, 15);
            selectedTextSize = (int) ta.getDimension(R.styleable.ViewPagerIndicator_item_selected_text_size, 15);
            itemPaddingLeft = (int) ta.getDimension(R.styleable.ViewPagerIndicator_item_padding_left, 15);
            itemPaddingRight = (int) ta.getDimension(R.styleable.ViewPagerIndicator_item_padding_right, 15);
            unselectedTextColor = ta.getColor(R.styleable.ViewPagerIndicator_item_unselected_text_color, unselectedTextColor);
            selectedTexColor = ta.getColor(R.styleable.ViewPagerIndicator_item_selected_text_color, selectedTexColor);
            itemHeight = (int) ta.getDimension(R.styleable.ViewPagerIndicator_item_height, 15);
            ta.recycle();
        }
        setHorizontalScrollBarEnabled(false);
        mLinearLayout = new LinearLayout(getContext());
        addView(mLinearLayout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        mLinearLayout.setGravity(Gravity.CENTER_VERTICAL);
        mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
        argbEvaluator = new ArgbEvaluator();
    }

    private void startAnimator(){
        mValueAnimator = new MyValueAnimator(currentItem, lastItem);
        mValueAnimator.setIntValues(unselectedTextSize, selectedTextSize);
        mValueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
        mValueAnimator.setDuration(200);
        mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (int) animation.getAnimatedValue();
                TextView currentTab = null;
                TextView lastTab = null;
                for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
                    TextView tab = (TextView) mLinearLayout.getChildAt(i);
                    Log.i("lzxlzx", "mValueAnimator.currentItem:" + mValueAnimator.currentItem + " mValueAnimator.lastItem:" + mValueAnimator.lastItem);
                    if (i == mValueAnimator.currentItem) {
                        currentTab = tab;
                    } else if (i == mValueAnimator.lastItem) {
                        lastTab = tab;
                    }
                }
                if (value - unselectedTextSize == animatorDifference) {
                    return;
                }
                animatorDifference = value - unselectedTextSize;
                Log.i("lzx", "animatorDifference:" + animatorDifference);
                if(currentTab != null){
                    float currentTextSize = unselectedTextSize + animatorDifference;
                    currentTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, currentTextSize);
                    Log.i("lzxlzx", "currentTextSize:" + currentTextSize);
                }
                if (lastTab != null) {
                    float lastTextSize = selectedTextSize - animatorDifference;
                    lastTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, selectedTextSize - animatorDifference);
                    Log.i("lzxlzx", "lastTextSize:" + lastTextSize);
                }
            }
        });
        mValueAnimator.start();
    }

    class MyValueAnimator extends ValueAnimator {
        public int currentItem;
        public int lastItem;

        public MyValueAnimator(int currentItem, int lastItem) {
            super();
            this.currentItem = currentItem;
            this.lastItem = lastItem;
        }
    }

    public void setUnselectedTextColor(int unselectedTextColor) {
        this.unselectedTextColor = unselectedTextColor;
    }

    public void setSelectedTexColor(int selectedTexColor) {
        this.selectedTexColor = selectedTexColor;
    }

    public void changeTextColor(int unselectedTextColor, int selectedTexColor) {
        this.unselectedTextColor = unselectedTextColor;
        this.selectedTexColor = selectedTexColor;
        for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
            TextView tab = (TextView) mLinearLayout.getChildAt(i);
            if (i == currentItem) {
                tab.setTextColor(selectedTexColor);
            } else {
                tab.setTextColor(unselectedTextColor);
            }
        }
    }

    public void setTitles(String[] titles) {
        mLinearLayout.removeAllViews();
        if (titles == null) {
            return;
        }
        for (int i = 0; i < titles.length; i++) {
            createItem(titles[i], i);
        }
    }

    public void setTitleList(List<String> titles) {
        mLinearLayout.removeAllViews();
        if (titles == null) {
            return;
        }
        this.titles = titles;
        for (int i = 0; i < titles.size(); i++) {
            createItem(titles.get(i), i);
        }
    }

    public static class Title {
        public String id;
        public String name;

        public Title(String id, String name) {
            this.id = id;
            this.name = name;
        }
    }

    private class ItemOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            if (viewPager != null) {
                int toItem = (Integer) v.getTag();
                viewPager.setCurrentItem(toItem);
            }
        }
    }

    private void createItem(String text, int index) {
        TextView textView = new TextView(getContext());
        textView.setText(text);
        if (mItemOnClickListener == null) {
            mItemOnClickListener = new ItemOnClickListener();
        }
        if (currentItem == index) {
            textView.setTextColor(selectedTexColor);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, selectedTextSize);
            textView.setTypeface(Typeface.DEFAULT_BOLD);
        } else {
            textView.setTextColor(unselectedTextColor);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, unselectedTextSize);
            textView.setTypeface(Typeface.DEFAULT);
        }
        textView.setGravity(Gravity.CENTER);
        textView.setTag(index);
        textView.setPadding(itemPaddingLeft, 0, itemPaddingRight, 0);
        textView.setOnClickListener(mItemOnClickListener);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
        layoutParams.height = itemHeight;
        mLinearLayout.addView(textView, layoutParams);
    }

    public void setupViewpager(ViewPager viewPager) {
        this.viewPager = viewPager;
        if (viewPager != null) {
            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                private int scrollingPosition;

                @Override
                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                    if (positionOffset != 0) {
                        Log.i("luzxluzx", "position:" + position + " currentItem:" + currentItem + " positionOffset:" + positionOffset + " positionOffsetPixels:" + positionOffsetPixels);
                        TextView currentTab = (TextView) mLinearLayout.getChildAt(position);
                        if (currentTab == null) {
                            return;
                        }
         /*               int currentColor = (int) (argbEvaluator.evaluate(positionOffset, selectedTexColor, unselectedTextColor));
                        currentTab.setTextColor(currentColor);*/
//                        int currentTextSize = (int) (selectedTextSize - (selectedTextSize - unselectedTextSize) * positionOffset + 0.5f);
////                        Log.i("luuzx", "currentTextSize:" + currentTextSize + "==" + currentTab.getTextSize());
//                        currentTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, currentTextSize);

                        TextView nextTab = (TextView) mLinearLayout.getChildAt(position + 1);
                        if (nextTab == null) {
                            return;
                        }
           /*             int nextColor = (int) (argbEvaluator.evaluate(positionOffset, unselectedTextColor, selectedTexColor));
                        nextTab.setTextColor(nextColor);*/
//                        int moveX = 0;
//                        int scrollX = 0;
//                        if(currentItem == position){
//                            moveX = startX + (int) (current.getWidth() * positionOffset);
//                            scrollX = (startX - ) + (int) (current.getWidth() * positionOffset);
//                        }else if(position < currentItem){
//                            moveX = startX - (int) (current.getWidth() *  (1 - positionOffset));
//                            scrollX = (startX - ) - (int) (current.getWidth() *  (1 - positionOffset));
//                        }
                        int scrollX = 0;
//                        Log.i("luzxzx", "lastPositionOffsetPixels:" + lastPositionOffsetPixels + " positionOffsetPixels:" + positionOffsetPixels);
                        boolean toRight = false;
                        boolean toLeft = false;
                        if (lastPositionOffsetPixels == 0) {
                            if (positionOffsetPixels < viewPager.getWidth() / 2f) {
                                toRight = true;
                            } else if (positionOffsetPixels > viewPager.getWidth() / 2f) {
                                toLeft = true;
                            }
                        } else {
                            if (lastPositionOffsetPixels < positionOffsetPixels) {
                                toRight = true;
                            } else if (lastPositionOffsetPixels > positionOffsetPixels) {
                                toLeft = true;
                            }
                        }
                        View current = null;
//                        if(currentItem == position){
//                            current = mLinearLayout.getChildAt(position);
//                        }else{
//                            current = mLinearLayout.getChildAt(position + 1);
//                        }
                        if (toRight || currentItem == position) {
                            current = mLinearLayout.getChildAt(position);
                            int currentWidth = current.getWidth();
                            int x = ((int) (currentWidth * positionOffset));
                            moveX = (int) (current.getX() + x);
                            Log.i("luzxzx", "moveX:" + moveX + "=current.getX():" + current.getX() + "+x:" + x);
                            Log.i("luzxzx", "last scrollX:" + getScrollX());
                            if (moveX > startScrollX) {
                                scrollX = moveX - startScrollX;
                                Log.i("luzxzx", "scrollX:" + scrollX);
                                scrollTo(scrollX, 0);
                            } else if (getScrollX() > 0) {
                                scrollX = 0;
                                Log.i("luzxzx", "scrollX:" + scrollX);
                                scrollTo(scrollX, 0);
                            }
                        } else if (toLeft || position < currentItem) {
                            lastPosition = position;
                            current = mLinearLayout.getChildAt(position + 1);
                            Log.i("luzxzx", "last scrollX:" + getScrollX());
                            if (getScrollX() > 0) {
                                int currentWidth = current.getWidth();
                                positionOffset = (1 - positionOffset);
                                int x = (int) (currentWidth * positionOffset);
                                moveX = (int) (current.getX() - x);
                                Log.i("luzxzx", "moveX:" + moveX + "=current.getX():" + current.getX() + "-x:" + x);
                                scrollX = moveX - startScrollX;
                                Log.i("luzxzx", "scrollX:" + scrollX);
                                scrollTo(scrollX, 0);
                            }
                        }
//                        int nextTextSize = (int) (unselectedTextSize + (selectedTextSize - unselectedTextSize) * positionOffset + 0.5f);
////                        Log.i("luuzx", "nextTextSize:" + nextTextSize + "==" + nextTab.getTextSize());
//                        nextTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, nextTextSize);
                    }
                    lastPositionOffsetPixels = positionOffsetPixels;
                }

                @Override
                public void onPageSelected(int position) {
                    lastItem = currentItem;
                    currentItem = position;
                    Log.i("luzxzx", "onPageSelected currentItem:" + currentItem);
                    if(currentItem != lastItem){
                        for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
                            TextView tab = (TextView) mLinearLayout.getChildAt(i);
                            if (i == currentItem) {
                                tab.setTextColor(selectedTexColor);
                                tab.setTypeface(Typeface.DEFAULT_BOLD);
                            } else {
                                tab.setTextColor(unselectedTextColor);
                                tab.setTypeface(Typeface.DEFAULT);
                            }
                        }
                        startAnimator();
                    }
                }

                @Override
                public void onPageScrollStateChanged(int state) {
                }
            });
        }
        selectTab(currentItem);
    }

    public void selectTab(int position) {
        if (mLinearLayout.getChildCount() > 0) {
            TextView currentTab = (TextView) mLinearLayout.getChildAt(currentItem);
            if (currentTab != null) {
                currentTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, unselectedTextSize);
                currentTab.setTextColor(unselectedTextColor);
                currentTab.setTypeface(Typeface.DEFAULT);
            }
            final TextView newCurrentTab = (TextView) mLinearLayout.getChildAt(position);
            if (newCurrentTab != null) {
                newCurrentTab.setTextSize(TypedValue.COMPLEX_UNIT_PX, selectedTextSize);
                newCurrentTab.setTextColor(selectedTexColor);
                newCurrentTab.setTypeface(Typeface.DEFAULT_BOLD);
                newCurrentTab.post(new Runnable() {
                    @Override
                    public void run() {
                        int x = (int) newCurrentTab.getX();
                        scrollTo(x - startScrollX, 0);
                        if (viewPager != null) {
                            viewPager.setCurrentItem(position);
                        }
                    }
                });
                currentItem = position;
            }
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        startScrollX = getMeasuredWidth() / 2;
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Bundle bundle = new Bundle();
        Parcelable superData = super.onSaveInstanceState();
        bundle.putParcelable("super_data", superData);
        bundle.putInt("currentItem", currentItem);
        bundle.putInt("lastItem", lastItem);
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        Bundle bundle = (Bundle) state;
        Parcelable superData = bundle.getParcelable("super_data");
        currentItem = bundle.getInt("currentItem");
        lastItem = bundle.getInt("lastItem");
        super.onRestoreInstanceState(superData);
    }

    public int getCurrentItem() {
        return currentItem;
    }
}
